package com.miui.theme.custom.screen

import android.widget.Toast
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.miui.theme.custom.components.AppTopAppBar
import com.miui.theme.custom.navigation.AppScreen
import com.miui.theme.custom.navigation.currentComposeNavigator
import com.miui.theme.custom.viewmodel.DataState
import com.miui.theme.custom.viewmodel.TableCrudViewModel
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class) // 需要为 ListItem
@Composable
fun TableCrudScreen(
    tableName: String,
    viewModel: TableCrudViewModel = koinViewModel()
) {
    val navigator = currentComposeNavigator
    val dataState by viewModel.dataState.collectAsState()
    val columns by viewModel.columns.collectAsState()
    val data by viewModel.data.collectAsState()
    val error by viewModel.error.collectAsState()

    var showAddDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf<Map<String, Any?>?>(null) }
    var showEditDialog by remember { mutableStateOf<Map<String, Any?>?>(null) }

    LaunchedEffect(tableName) {
        viewModel.loadTableData(tableName)
    }

    Scaffold(
        topBar = {
            AppTopAppBar(
                title = "表: $tableName",
                onNavigateUp = { navigator.navigateUp() },
                actions = {
                    IconButton(onClick = {
                        navigator.navigate(AppScreen.TableDetails(tableName))
                    }) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "表结构"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { showAddDialog = true }) {
                Icon(Icons.Default.Add, contentDescription = "添加数据")
            }
        }
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding),
            // .padding(16.dp), // 移除外层padding，让LazyColumn全宽
            contentAlignment = Alignment.Center
        ) {
            when (dataState) {
                DataState.Loading -> CircularProgressIndicator()
                DataState.Error -> Text(
                    "加载失败: $error",
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(16.dp)
                )
                DataState.Success -> {
                    if (data.isEmpty()) {
                        // 优化：空状态提示
                        Text(
                            text = "这张表没有数据。\n点击右下角按钮添加。",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center
                        )
                    } else {
                        // 优化：使用 LazyColumn + ListItem
                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = PaddingValues(vertical = 8.dp)
                        ) {
                            items(data) { rowData ->
                                RowDataListItem(
                                    rowData = rowData,
                                    onEdit = {
                                        showEditDialog = rowData // <-- 触发编辑
                                    },
                                    onDelete = {
                                        showDeleteDialog = rowData
                                    }
                                )
                                HorizontalDivider()
                            }
                        }
                    }
                }
                else -> {} // Idle
            }
        }
    }

    showEditDialog?.let { rowData ->
        val primaryKeyColumn = columns.firstOrNull()

        EditDataDialog(
            columns = columns.filterNot { it == primaryKeyColumn }, // 不允许编辑主键
            initialData = rowData,
            primaryKeyName = primaryKeyColumn,
            onDismiss = { showEditDialog = null },
            onConfirm = { updatedData ->
                if (primaryKeyColumn != null) {
                    val primaryKeyValue = rowData[primaryKeyColumn]
                    viewModel.updateData(tableName, (primaryKeyColumn to primaryKeyValue), updatedData)
                }
                showEditDialog = null
            }
        )
    }

    if (showAddDialog) {
        AddDataDialog(
            columns = columns.filterNot { it.lowercase() == "id" },
            onDismiss = { showAddDialog = false },
            onConfirm = { newData ->
                viewModel.insertData(tableName, newData)
                showAddDialog = false
            }
        )
    }

    showDeleteDialog?.let { rowData ->
        val primaryKeyColumn = columns.firstOrNull()
        val primaryKeyValue = rowData[primaryKeyColumn]

        AlertDialog(
            onDismissRequest = { showDeleteDialog = null },
            title = { Text("确认删除") },
            text = { Text("你确定要删除这条记录吗？\n${primaryKeyColumn}: $primaryKeyValue") },
            confirmButton = {
                Button(
                    onClick = {
                        if (primaryKeyColumn != null) {
                            viewModel.deleteData(tableName, primaryKeyColumn to primaryKeyValue)
                        }
                        showDeleteDialog = null
                    },
                    // 优化：使用规范的 Error 颜色
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = null }) {
                    Text("取消")
                }
            }
        )
    }
}

/**
 * 优化：使用 ListItem 替换 Card
 */
@Composable
private fun RowDataListItem(
    rowData: Map<String, Any?>,
    onEdit: () -> Unit,
    onDelete: () -> Unit
) {
    val primaryKey = rowData.keys.firstOrNull()
    val primaryValue = rowData[primaryKey]?.toString() ?: "N/A"

    // 将其他数据显示为一行
    val supportingText = rowData.filterKeys { it != primaryKey }
        .map { "${it.key}: ${it.value}" }
        .joinToString(" | ")

    ListItem(
        headlineContent = {
            Text(
                "$primaryKey: $primaryValue",
                style = MaterialTheme.typography.titleSmall
            )
        },
        supportingContent = {
            Text(
                supportingText,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                style = MaterialTheme.typography.bodyMedium
            )
        },
        trailingContent = {
            Row {
                IconButton(onClick = onEdit) {
                    Icon(Icons.Default.Edit, contentDescription = "编辑")
                }
                IconButton(onClick = onDelete) {
                    Icon(Icons.Default.Delete, contentDescription = "删除", tint = MaterialTheme.colorScheme.error)
                }
            }
        },
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) // 增加列表项边距
    )
}

/**
 * 优化：添加数据的对话框
 */
@Composable
private fun AddDataDialog(
    columns: List<String>,
    onDismiss: () -> Unit,
    onConfirm: (Map<String, String>) -> Unit
) {
    val formState = remember { mutableStateMapOf<String, String>().apply {
        columns.forEach { put(it, "") }
    }}
    val context = LocalContext.current

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("添加新记录") },
        text = {
            // 限制对话框高度，使内容可滚动
            LazyColumn(modifier = Modifier.heightIn(max = 300.dp)) {
                items(columns) { colName ->
                    OutlinedTextField(
                        value = formState[colName] ?: "",
                        onValueChange = { formState[colName] = it },
                        label = { Text(colName) },
                        modifier = Modifier
                            .fillMaxWidth() // 优化：填满宽度
                            .padding(vertical = 4.dp),
                        singleLine = true
                    )
                }
            }
        },
        confirmButton = {
            Button(onClick = {
                if (formState.values.any { it.isBlank() }) {
                    Toast.makeText(context, "所有字段都不能为空", Toast.LENGTH_SHORT).show()
                } else {
                    onConfirm(formState.toMap())
                }
            }) {
                Text("添加")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 优化：编辑数据的对话框
 */
@Composable
private fun EditDataDialog(
    columns: List<String>, // 仅包含非主键的列
    initialData: Map<String, Any?>,
    primaryKeyName: String?,
    onDismiss: () -> Unit,
    onConfirm: (Map<String, String>) -> Unit
) {
    // 将所有值初始化为字符串
    val formState = remember {
        mutableStateMapOf<String, String>().apply {
            columns.forEach { colName ->
                put(colName, initialData[colName]?.toString() ?: "")
            }
        }
    }
    val context = LocalContext.current

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("编辑记录") },
        text = {
            LazyColumn(modifier = Modifier.heightIn(max = 300.dp)) {
                // 显示主键（不可编辑）
                item {
                    if (primaryKeyName != null) {
                        OutlinedTextField(
                            value = initialData[primaryKeyName]?.toString() ?: "N/A",
                            onValueChange = {},
                            label = { Text("$primaryKeyName (主键)") },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            enabled = false // 不可编辑
                        )
                    }
                }
                // 显示其他字段（可编辑）
                items(columns) { colName ->
                    OutlinedTextField(
                        value = formState[colName] ?: "",
                        onValueChange = { formState[colName] = it },
                        label = { Text(colName) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 4.dp),
                        singleLine = true
                    )
                }
            }
        },
        confirmButton = {
            Button(onClick = {
                if (formState.values.any { it.isBlank() }) {
                    Toast.makeText(context, "所有字段都不能为空", Toast.LENGTH_SHORT).show()
                } else {
                    onConfirm(formState.toMap())
                }
            }) {
                Text("保存")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}